﻿<%@ WebHandler Language="C#" Class="BomChangeErpConfirmVue3PageHandler" %>

/* Description:工艺更换集件校准
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan 
 * create Date:2025.10.22
 */

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Collections;
using System.IO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using BusinessRule.DTO;
using System.Configuration;

public class BomChangeErpConfirmVue3PageHandler : IHttpHandler, IRequiresSessionState
{
    class Result
    {
        public object data { get; set; }
        public Meta meta { get; set; }
        public int total { get; set; }
        public class Meta
        {
            public int status;
            public string msg;
            public Meta(int status, string msg)
            {
                this.status = status;
                this.msg = msg;
            }
        }
    }

    BusinessRule.IBusiness.uLMSCommonIBusiness m_Common = BusinessRule.BusinessFactory.uMESBusinessFactory.instance.GetuLMSCommonObject();
    CurrentUserInfo m_UserInfo = new CurrentUserInfo();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getUserInfo":
                        r = getUserInfo();//查询当前用户信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getContainerInfo":
                        r = getContainerInfo(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getCurrentBom":
                        r = getCurrentBom(jObject);//当前工艺集件信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getHistoryBom":
                        r = getHistoryBom(jObject);//历史工艺集件信息
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDiff":
                        r = getDiff(jObject);//集件差异
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "resendData":
                        r = resendData(jObject);//推送
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getUserInfo()
    {
        Result r = new Result();
        r.data = m_UserInfo;
        r.total = 0;
        r.meta = m_UserInfo == null ? new Result.Meta(500, "当前未登录") : new Result.Meta(200, "请求成功");
        return r;
    }

    Result getContainerInfo(JObject jObject)
    {
        string sql = @"
SELECT DISTINCT mfg.mfgorderid,mfg.mfgordername,mfg.qty mfgqty,cci.containername,cci.qty,cci.workflowname || ':' || cci.workflowrevision workflowinfo,cci.workflowstepname,
       DECODE(cci.containertype,2,'批量加工',3,'批量带子序号') containertype,cci.plannedstartdate,cci.plannedcompletiondate,cci.workflowid,c.originalqty,cci.containerid
FROM containercurrentinfo cci
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN orderstatus od ON mfg.orderstatusid = od.orderstatusid
LEFT JOIN factory f ON f.factoryid = cci.originalfactoryid
INNER JOIN bom b ON b.workflowid = cci.workflowid
LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
WHERE cci.containertype <> '7' AND c.originalqty = mfg.qty
      AND cci.isinstore = 0
      AND NVL(od.orderstatusname,'打开') <> '关闭'";
        //件号
        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            sql += string.Format(" AND cci.productname LIKE '%{0}%'", jObject["productname"].ToString());
        }

        //订单号
        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            sql += string.Format(" AND mfg.mfgordername LIKE '%{0}%'", jObject["mfgordername"].ToString());
        }

        //批次号
        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            sql += string.Format(" AND cci.containername LIKE '%{0}%'", jObject["containername"].ToString());
        }

        //主制分厂
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND mfg.factoryid = '{0}'", jObject["factoryid"].ToString());
        }

        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(jObject["currentPage"]);//页码
        paraPage.PageSize = Convert.ToInt32(jObject["pageSize"]);//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        DataTable dtResult = result.DBTable;

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(result.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //当前工艺集件信息
    Result getCurrentBom(JObject jObject)
    {
        string sql = @"
SELECT s.specno,s.opdesc specname,pbn.productname,pml.qtyrequired * c.originalqty qty
FROM containercurrentinfo cci
LEFT JOIN container c ON c.containerid = cci.containerid
LEFT JOIN workflow wf ON wf.workflowid = cci.workflowid
--bom信息
INNER JOIN bom b ON b.workflowid = wf.workflowid
LEFT JOIN bombase bb ON bb.bombaseid = b.bombaseid
LEFT JOIN productmateriallistitem pml ON pml.bomid = b.bomid
--bom工序信息
LEFT JOIN specbase sb ON sb.specbaseid=pml.specbaseid
LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid, pml.specid)
LEFT JOIN specbase sb2 ON sb2.specbaseid = s.specbaseid
--子零件信息
LEFT JOIN productbase pb ON pb.productbaseid = pml.productbaseid
LEFT JOIN product p ON p.productid =NVL(pb.revofrcdid, pml.productid)
LEFT JOIN productbase pbn ON pbn.productbaseid=p.productbaseid
WHERE cci.containerid = '{0}'
ORDER BY s.specno,pbn.productname";
        sql = string.Format(sql, jObject["containerid"].ToString());
        DataTable dtBom = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtBom.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtBom;
        r.total = dtBom.Rows.Count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //历史工艺集件信息
    Result getHistoryBom(JObject jObject)
    {
        string sql = @"
SELECT erp.specno,erp.specname,erp.productname,erp.qty 
FROM erp_send_material erp 
WHERE erp.mfgordername = '{0}' 
ORDER BY erp.specno,erp.productname";
        sql = string.Format(sql, jObject["mfgordername"].ToString());
        DataTable dtBom = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtBom.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtBom;
        r.total = dtBom.Rows.Count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //集件差异
    Result getDiff(JObject jObject)
    {
        string mfgordername = jObject["mfgordername"].ToString();
        string sql = @"
SELECT t.id,t.specno,t.specname,t.productname,t.diffqty,t.mfgordername,
       DECODE(t.oper_type,1,'增加数量',2,'减少数量',3,'增加条目',4,'删除条目') oper_type,t.oper_type oper_type2,
       t.erp_return_date,t.createdate,'已推送' send_status,
       DECODE(t.erp_status,0,'失败',1,'成功') erp_status,t.erp_msg
FROM erp_mes_bom_diff t
WHERE t.mfgordername = '{0}' AND t.diff_type = 'MES'";
        sql = string.Format(sql, mfgordername);
        DataTable dtDiff = DatabaseHelper.Query_ReturnDatTable(sql);
        foreach (DataColumn col in dtDiff.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtDiff;
        r.total = dtDiff.Rows.Count;
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    //推送
    Result resendData(JObject jObject)
    {
        Result r = new Result();
        string mfgordername = jObject["mfgordername"].ToString();
        string containerid = jObject["containerid"].ToString();
        string sql = @"
SELECT * FROM mes_send_erp_diff t WHERE t.issend = 0 AND t.mfgordername = '{0}' AND t.containerid = '{1}' AND t.diff_type = 'MES'
";
        sql = string.Format(sql, mfgordername, containerid);
        DataTable dt = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dt.Rows.Count == 0)
        {
            string insertSql = @"INSERT INTO mes_send_erp_diff(mfgordername,containerid,diff_type) VALUES('{0}','{1}','MES')";
            insertSql = string.Format(insertSql, mfgordername, containerid);
            int count = DatabaseHelper.ExecuteSql(insertSql);
            r.data = count > 0;
            r.total = 0;
            r.meta = new Result.Meta(200, "请求成功");
            return r;
        }
        r.data = false;
        r.total = 0;
        r.meta = new Result.Meta(200, "推送失败");
        return r;
    }
}